package io.adrainty.gbatis.datasource;

import io.adrainty.gbatis.exception.CoreException;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Arrays;
import java.util.logging.Logger;

/**
 * UNPOOLED 数据源实现类
 * @author adrainty
 * @version v1.0.0
 * @since 2024/1/14 22:46
 */
public class UnPooledDataSource implements DataSource {

    private final String url;

    private final String username;

    private final String password;

    public UnPooledDataSource(String driverName, String url, String username, String password) {
        try {
            Class<?> driverClass = Class.forName(driverName);
            if (!Arrays.asList(driverClass.getInterfaces()).contains(Driver.class)) {
                throw new CoreException(String.format("Class [%s] is not matched Driver.", driverName));
            }
        } catch (ClassNotFoundException e) {
            throw new CoreException(String.format("Class [%s] not found.", driverName));
        }
        this.url = url;
        this.username = username;
        this.password = password;
    }

    @Override
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(this.url, this.username, this.password);
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return DriverManager.getConnection(this.url, username, password);
    }

    @Override
    public PrintWriter getLogWriter() {
        return DriverManager.getLogWriter();
    }

    @Override
    public void setLogWriter(PrintWriter out) {
        DriverManager.setLogWriter(out);
    }

    @Override
    public void setLoginTimeout(int seconds) {
        DriverManager.setLoginTimeout(seconds);
    }

    @Override
    public int getLoginTimeout() {
        return DriverManager.getLoginTimeout();
    }

    @Override
    public Logger getParentLogger() {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) {
        return false;
    }
}
